<script setup lang="ts">
import { ref } from 'vue'
import { logout, signout, signoutSendCode } from '@/api/login'
import { pageUrl } from '@/utils/constants'
import { useMemberStore, useSettingStore } from '@/stores'


const memberStore = useMemberStore()
const settngStore = useSettingStore()

//退出登录
const onLogout = () => {
  uni.showModal({
    content: 'Are you sure you want to log out?',
    cancelText: 'cancel',
    confirmText: 'Log out',
    success: (res) => {
      if (res.confirm) {
        logout().then(() => {
          //清空信息 回首页
          useMemberStore().clearProfile()
          uni.showToast({
            title: 'Logged out success',
            icon: 'success',
          })
          setTimeout(() => {
            uni.reLaunch({ url: `${pageUrl['index']}` })
          }, 1500)
        })
      }
    },
  })
}

// 跳转富文本
const toRichTextPage = (type: string) => {
  const agreements = settngStore.data.agreement

  const content = encodeURIComponent(agreements[type as keyof typeof agreements])

  uni.navigateTo({
    url: `${pageUrl['rich-text']}?content=${content}`,
  })
}

const resetPwdRef = ref(null)
const email = ref(memberStore.profile?.email || '')
const verificationCode = ref('')
const isCounting = ref(false)
const countdown = ref(0)
let timer: number | undefined = undefined

// console.log(memberStore.profile)

const requestVerificationCode = async (event: Event) => {
  event.preventDefault(); // 阻止默认行为
  // Validate email format
  if (!email.value) {
    uni.showToast({
      title: 'Please enter email first',
      icon: 'none'
    })
    return
  }

  // Check if email format is valid
  if (!/^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(email.value)) {
    uni.showToast({
      title: 'Incorrect email format',
      icon: 'none'
    })
    return
  }

  try {
    // 开始倒计时
    isCounting.value = true
    countdown.value = 60

    // 清除之前的定时器
    if (timer) {
      clearInterval(timer)
    }

    // 设置新的定时器
    timer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(timer)
        isCounting.value = false
      }
    }, 1000)

    // Send verification code
    const res = await signoutSendCode(email.value)
    if (res.code === 200) {
      uni.showToast({
        title: 'Verification code sent successfully',
        icon: 'success'
      })
    } else {
      uni.showToast({
        title: res.msg || 'Failed to send verification code',
        icon: 'none'
      })
      // Reset countdown on failure
      clearInterval(timer)
      isCounting.value = false
      countdown.value = 0
    }
  } catch (error) {
    // Reset countdown on error
    if (timer) {
      clearInterval(timer)
    }
    isCounting.value = false
    countdown.value = 0
    uni.showToast({
      title: 'Failed to send verification code',
      icon: 'error'
    })
  }
}

const cancelAccount = () => {
  // Validate inputs
  if (!email.value) {
    uni.showToast({
      title: 'Please enter your email',
      icon: 'none'
    })
    return
  }

  if (!verificationCode.value) {
    uni.showToast({
      title: 'Please enter verification code',
      icon: 'none'
    })
    return
  }

  // Implement account cancellation logic here
  uni.showLoading({ title: 'Processing...' })

  // Call API to cancel account (add your API call here)
  // Example:
  signout({
    email: email.value,
    code: verificationCode.value
  }).then(res => {
    if (res.code === 200) {
      useMemberStore().clearProfile()
      uni.showToast({
        title: 'canceled account success',
        icon: 'success',
      })
      setTimeout(() => {
        uni.reLaunch({ url: `${pageUrl['index']}` })
      }, 1500)
      return
      // Log out and redirect to login page
      // logout()
    } else {
      uni.showToast({
        title: res.msg || 'Failed to cancel account',
        icon: 'none'
      })
    }
  }).catch(error => {
    uni.showToast({
      title: 'An error occurred',
      icon: 'error'
    })
  }).finally(() => {
    uni.hideLoading()
    resetPwdRef.value.close()
  })

  // For now, just show a success message and close the popup
  // setTimeout(() => {
  //   uni.hideLoading()
  //   uni.showToast({
  //     title: 'Account cancellation demo',
  //     icon: 'success'
  //   })
  //   resetPwdRef.value?.close()

  // }, 1500)
}
const cancelDialog = () => {
  resetPwdRef.value?.close()
}
// Add this method to show the popup
const showCancelAccountPopup = () => {
  email.value = memberStore.profile?.email || ''
  verificationCode.value = ''
  isCounting.value = false
  countdown.value = 0
  if (timer) {
    clearInterval(timer)
    timer = undefined
  }
  resetPwdRef.value?.open()
}


</script>

<template>
  <view class="viewport">
    <view class="list">
      <button hover-class="none" class="item arrow content">
        Current Version
        <text class="content-text">{{ settngStore.data.version }}</text>
      </button>
      <button hover-class="none" class="item arrow" @tap="toRichTextPage('user_agreement')">
        Terms of Service
      </button>
      <button hover-class="none" class="item arrow" @tap="toRichTextPage('privacy_agreement')">
        Privacy Policy
      </button>
      <button hover-class="none" class="item arrow" @tap="toRichTextPage('about_us_agreement')">
        About Us
      </button>
      <!-- #ifdef MP-WEIXIN -->
      <button hover-class="none" class="item arrow" open-type="openSetting">Permission Settings</button>
      <button hover-class="none" class="item arrow" open-type="feedback">Feedback</button>
      <button hover-class="none" class="item arrow" open-type="contact">Contact Us</button>
      <!-- #endif -->
      <!-- <view class="item" @click="showCancelAccountPopup">
        <text class="icon icon-delete"></text>
        <text class="text">Cancel Account</text>
        <text class="icon icon-right"></text>
      </view> -->
      <button hover-class="none" class="item arrow" @tap="showCancelAccountPopup()">
        Cancel Account
      </button>
    </view>

    <!-- 操作按钮 -->
    <view class="action" v-if="memberStore.profile">
      <view class="button" @tap="onLogout">Log Out</view>
    </view>
  </view>

  <uni-popup ref="resetPwdRef" type="dialog">
    <div class="cancel-account-container">
      <div class="title">Cancel Account</div>
      <div class="subtitle">Are you sure you want to cancel your account?</div>
      <div class="input-container">
        <input type="text" placeholder="Email" v-model="email" disabled>
      </div>
      <div class="verification-container">
        <input type="text" placeholder="Verification Code" v-model="verificationCode" class="verification-input">
        <button :disabled="isCounting" class="verification-btn" @click="requestVerificationCode">
          {{ isCounting ? `${countdown}s` : "Get Code" }}
        </button>
      </div>
      <div class="button-container">
        <button type="primary" @click="cancelAccount">Cancel Account</button>
        <button type="default" @click="cancelDialog">Cancel</button>
      </div>
      <div class="tip">Please enter your email and the verification code sent to your email to cancel your account.
      </div>
      <div class="tip">After canceling your account, you will no longer be able to log in to the app.</div>
    </div>
  </uni-popup>
</template>

<style lang="scss" scoped>
page {
  background-color: #f7f7f8;
}

.viewport {
  padding: 20rpx;
}

/* 列表 */
.list {
  padding: 0 20rpx;
  background-color: #fff;
  margin-bottom: 20rpx;
  border-radius: 10rpx;

  .item {
    line-height: 90rpx;
    padding-left: 10rpx;
    font-size: 30rpx;
    color: #333;
    border-top: 1rpx solid #ddd;
    position: relative;
    text-align: left;
    border-radius: 0;
    background-color: #fff;

    &::after {
      width: auto;
      height: auto;
      left: auto;
      border: none;
    }

    &:first-child {
      border: none;
    }

    &::after {
      right: 5rpx;
    }
  }

  .content {
    display: flex;
    justify-content: space-between;

    .content-text {
      margin-right: 25rpx;
      color: #aaa;
    }
  }

  .arrow::after {
    content: '\e6c2';
    position: absolute;
    top: 50%;
    color: #ccc;
    font-family: 'iconfont' !important;
    font-size: 32rpx;
    transform: translateY(-50%);
  }
}

/* 操作按钮 */
.action {
  text-align: center;
  line-height: 90rpx;
  margin-top: 40rpx;
  font-size: 32rpx;
  color: #333;

  // display: grid;
  // gap: 20rpx;
  // grid-template-columns: repeat(2, 1fr);
  .button {
    background-color: #fff;
    margin-bottom: 20rpx;
    border-radius: 10rpx;
  }
}

.cancel-account-container {
  padding: 30rpx;
  width: 80vw;
  max-width: 600rpx;
  background-color: #fff;
}

.cancel-account-container .title {
  font-size: 36rpx;
  font-weight: bold;
  text-align: center;
  margin-bottom: 20rpx;
}

.cancel-account-container .subtitle {
  font-size: 28rpx;
  text-align: center;
  margin-bottom: 30rpx;
  color: #666;
}

.cancel-account-container .input-container {
  margin-bottom: 20rpx;
}

.cancel-account-container input {
  width: 100%;
  height: 80rpx;
  border: 1px solid #ddd;
  border-radius: 8rpx;
  padding: 0 20rpx;
  box-sizing: border-box;
  font-size: 28rpx;
}

.cancel-account-container .verification-container {
  display: flex;
  margin-bottom: 30rpx;
}

.cancel-account-container .verification-input {
  flex: 1;
  margin-right: 20rpx;
}

.cancel-account-container .verification-btn {
  width: 200rpx;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  background-color: #ff5f3c;
  color: #fff;
  border-radius: 8rpx;
  font-size: 24rpx;
}

.cancel-account-container .verification-btn:disabled {
  background-color: #ccc;
}

.cancel-account-container .button-container {
  display: flex;
  justify-content: space-between;
  margin-top: 30rpx;
}

.cancel-account-container button {
  flex: 1;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  border-radius: 8rpx;
  margin: 0 10rpx;
  font-size: 28rpx;
}

.cancel-account-container button[type="primary"] {
  background-color: #ff5f3c;
  color: #fff;
}

.cancel-account-container button[type="default"] {
  background-color: #f5f5f5;
  color: #333;
  border: 1px solid #ddd;
}

.cancel-account-container .tip {
  margin-top: 20rpx;
  font-size: 24rpx;
  color: #999;
  text-align: center;
}
</style>
